import { ExecutionContext, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/api/entities/user.entity';
import { Repository } from 'typeorm';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}
  async findUserByOpenId(openId: string) {
    const userInfo: User = await this.userRepository.findOne({
      where: {
        openId,
      },
    });

    return userInfo;
  }

  async registerUser(user: User): Promise<User> {
    const newUser = await this.userRepository.save(user);
    return newUser;
  }

  async getUserInfoByUserId(userId: number) {
    const userInfo = await this.userRepository.findOne({
      where: {
        userId,
      },
    });
    console.log(userInfo);

    return userInfo;
  }

  async getCurrentUserInfo(request: Request) {
    const userId = request['userId']; // 从请求中获取用户 ID
    if (!userId) {
      throw new Error('当前用户未登录！');
    }

    const user = await this.userRepository.findOneBy({ userId });
    if (!user) {
      throw new Error('当前用户不存在！');
    }

    return user;
  }
}
